import axios from "axios";
import { ElMessage } from "element-plus";
import { useRouter } from "vue-router";
// import useDataStore from "../store";
// import { storeToRefs } from 'pinia';
import app from "../main";

const router = useRouter()
// const dataStore = useDataStore()
// const { userInfo, isLogin } = storeToRefs(dataStore)




/**
 * axios的二次封装
 */
class Http {
    constructor() {
        const loadingOption = {
            fullScreen: true
        }
        let loadingInstance
        this.instance = axios.create({
            // baseURL: "http://localhost:8080/api",     // development
            // baseURL: "http://8.138.1.3:8889/api",    //production
            baseURL: import.meta.env.VITE_BASE_URL,
            timeout: 20000
        })

        // 添加请求拦截器
        this.instance.interceptors.request.use((config) => {
            loadingInstance = app.config.globalProperties.$loading(loadingOption)
            const token = localStorage.getItem('token')
            if (token) {
                config.headers.Authorization = token
            }
            return config
        }, (error) => {
            return Promise.reject(error)
        })

        // 添加响应拦截器
        this.instance.interceptors.response.use((response) => {
            if (response.status == 200 || response.data.code == 200) {
                loadingInstance.close()
                return response.data
            } else {
                ElMessage({
                    type: 'error',
                    message: response.data.msg
                })
                // dataStore.setUserInfo({})
                // dataStore.setIsLogin(false)
                // router.push({ name: 'login' })
                loadingInstance.close()
                return response.data
                // new Error("请求失败")
            }
        }, (error) => {
            return Promise.reject(error)
        })
    }

    /**
     * @description
     * @param {string} url 
     * @param {object} data 
     * @param {object} config 
     */
    get(url, data = {}, config = {}) {
        return this.instance.get(url, {
            params: data,
            ...config
        })
    }

    /**
     * @description
     * @param {string} url 
     * @param {object} data 
     * @param {object} config 
     */
    post(url, data = {}, config = {}) {
        return this.instance.post(url, data, config)
    }

    /**
     * @description
     * @param {string} url 
     * @param {object} data 
     * @param {object} config 
     */
    delete(url, data = {}, config = {}) {
        return this.instance.delete(url, {
            params: data,
            ...config
        })
    }
    /**
        * @description
        * @param {string} url 
        * @param {object} data 
        * @param {object} config 
        */
    patch(url, data = {}, config = {}) {
        return this.instance.patch(url, data, config)
    }





}

const request = new Http()

export default request